<template>
  <div class="bf-table h-full" ref="tableContainer">
    <NDataTable
      :columns="initColumns"
      :data="props.data"
      :checked-row-keys="props.selectRowKeys"
      :bordered="false"
      :single-line="false"
      :max-height="tableHeight"
      :scroll-x="props.scrollX"
      :row-key="(row) => row[rowKey]"
      @update:checked-row-keys="updateRowKey"
      v-bind="{ ...props.tableProps }"
    />
  </div>
</template>

<script setup lang="ts">
import { debounce } from '@/utils/common.util'
import { TableProps } from 'naive-ui'
import { computed, h, onMounted, onUnmounted, ref, useSlots } from 'vue'
import { BFTableColumn } from './bf-table'
type BFTableProps = {
  columns: BFTableColumn[]
  data?: any[]
  selectRowKeys?: any[]
  selectRows?: any[]
  rowKey?: any
  scrollX?: number | string
  tableProps?: TableProps
}

interface BFTableEmits {
  (e: 'update:selectRowKeys', rowKeys: any[]): void
  (e: 'update:selectRows', rows: any[]): void
}
const slots = useSlots()
let tableContainer = ref<HTMLElement>()

const props = withDefaults(defineProps<BFTableProps>(), {
  rowKey: 'id',
  scrollX: '100%',
  data: () => []
})

const initColumns = computed(() => {
  const colList: BFTableColumn[] = []
  props.columns.forEach((item: any) => {
    if (item.slot) {
      if (!item.render) {
        item.render = function (rowData: any, rowIndex: number) {
          return h('div', slots[item.key]!({ rowData, rowIndex }))
        }
      }
    }
    colList.push({ ...item })
  })
  return colList
})

const emits = defineEmits<BFTableEmits>()

const updateRowKey = (keys: any[], rows: any[]) => {
  emits('update:selectRowKeys', keys)
  emits('update:selectRows', rows)
}

let tableHeight = ref(400)
const autoTableHeightSize = debounce(() => {
  let { height } = tableContainer.value!.getClientRects()[0]
  let header = document.querySelector('.n-data-table-base-table-header')
  let headerHeight = header!.getClientRects()
  tableHeight.value = height - headerHeight[0].height
}, 200)

onMounted(() => {
  autoTableHeightSize()
  window.addEventListener('resize', autoTableHeightSize)
})

onUnmounted(() => {
  window.removeEventListener('resize', autoTableHeightSize)
})
</script>

<style scoped lang="scss"></style>
